package com.H1023.service;

import com.H1023.dao.ReaderMapper;
import com.H1023.pojo.Reader;
import com.H1023.pojo.ReaderLend;

import java.util.List;

/**
 * @author MSI-NB
 * @date 2021/10/10 20:50
 */
public class ReaderServiceImpl implements ReaderService {
    private ReaderMapper readerMapper;

    public void setReaderMapper(ReaderMapper readerMapper) {
        this.readerMapper = readerMapper;
    }

    /**
     * 查询所有读者
     *
     * @return 读者列表
     */
    public List<Reader> getAllReader() {
        return readerMapper.getAllReader();
    }

    /**
     * 根据读者id查询读者
     *
     * @param id
     * @return 读者
     */
    public Reader getReaderById(int id) {
        return readerMapper.getReaderById(id);
    }

    /**
     * 更新读者信息
     * @param reader
     * @return 执行条数
     */
    public int updateReader(Reader reader) {
        int count = 0;  //更新返回的标志
        try {
            if (readerMapper.queryReaderByName(reader.getReaderName()).size() != 0) {
                throw new Exception();
            } else {
                readerMapper.updateReader(reader);
            }

        } catch (Exception e) {
            System.out.println("插入失败！");
            count = -1;
        }
        return count;
    }

    /**
     * 新增读者
     *
     * @param reader
     * @return 执行条数
     */
    public int addReader(Reader reader) {
        int count = 0;  //插入返回的标志
        try {
            if (readerMapper.queryReaderByName(reader.getReaderName()).size() != 0) {
                throw new Exception();
            } else {
                readerMapper.addReader(reader);
            }

        } catch (Exception e) {
            System.out.println("插入失败！");
            count = -1;
        }
        return count;
    }

    /**
     * 模糊查询
     *
     * @return 读者信息
     * @Param name
     */
    public List<Reader> queryReaderByName(String readerName) {
        return readerMapper.queryReaderByName(readerName);
    }

    /**
     * 查询个人的借阅记录
     *
     * @return 借阅记录
     * @Param id
     */
    public List<ReaderLend> queryLendByReader(int id) {
        List<ReaderLend> readerLendList = readerMapper.queryLendByReader(id);
        //格式化借阅记录
        for (ReaderLend readerLend : readerLendList) {
            if (readerLend.getState() == 0) {
                readerLend.setState_toStr("否");
            } else {
                readerLend.setState_toStr("是");
            }
        }

        return readerLendList;
    }
}
